import { defineConfig } from 'vite';
import reactPlugin from '@vitejs/plugin-react';
import eslintPlugin from 'vite-plugin-eslint';
import { resolve } from 'path';
import postcssPresetEnv from 'postcss-preset-env';
import autoprefixer from 'autoprefixer';
// import legacy from '@vitejs/plugin-legacy';

const overrideBrowserslist = [
  '> 1%',
  'last 2 versions',
  'not dead',
  'not ie <= 11',
  'iOS >= 9',
  'Android >= 4.4',
  'Chrome >= 49',
  'Firefox >= 64',
  'Edge >= 15',
  'Safari >= 9',
];

export default defineConfig({
  base: './',
  server: {
    host: '0.0.0.0',
    open: true,
    port: 4399,
  },
  envPrefix: 'yjr',
  css: {
    postcss: {
      plugins: [
        postcssPresetEnv(),
        autoprefixer({
          overrideBrowserslist,
        }),
      ],
    },
    preprocessorOptions: {
      scss: {
        additionalData: `@import '@/global.scss';`,
      },
    },
    devSourcemap: true,
  },
  resolve: {
    alias: {
      '@': resolve(__dirname, './src'),
      '@cpt': resolve(__dirname, './src/components'),
      '@store': resolve(__dirname, './src/store.ts'),
    },
  },
  plugins: [
    // 需要兼容传统浏览器时解开下方注释
    // legacy({
    //   targets: overrideBrowserslist,
    // }),
    reactPlugin(),
    eslintPlugin({
      failOnError: false,
    }),
  ],
  build: {
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true,
      },
    },
    chunkSizeWarningLimit: 244,
    rollupOptions: {
      output: {
        // 需要手动分包时解开注释
        // manualChunks(id) {
        //   if (id.includes('node_modules')) {
        //     return id.split('node_modules/')[1].split('/')[0];
        //   }
        // },
        entryFileNames: 'js/entry.[hash].js',
        chunkFileNames: 'js/chunks/[name].[hash].js',
        assetFileNames({ name }) {
          const [ext] = name.split('.').slice(-1);
          if (/^(ttf|otf|woff)$/.test(ext))
            return 'iconfont/[name].[hash].[ext]';
          if (/^(mp3|mp4|wav|aif|aiff|ape)$/.test(ext))
            return 'media/[name].[hash].[ext]';
          if (/^(png|jpg|jpeg|gif|webp|svg|cvs)$/.test(ext))
            return 'imgs/[name].[hash].[ext]';
          return '[ext]/[name].[hash].[ext]';
        },
      },
    },
  },
});
